/**
 * Created by TomSean on 2017/7/11.
 */

var goblesn = new Date().getTime();

var data = [

];
$('#add-compont').dropdown();

$('#add-compont').find('.item').bind('click', function(event) {
    if (undefined == $(this).attr('data-value')) return;
    var typ = $(this).attr('data-type');
    var val = $(this).attr('data-value');
    var parent = $('.work-item.cur');
    parent = parent.length == 0 ? $('.work-content') : parent;
    createWorkElement(parent, typ, val);
});

$('#panel-config-frame .scale-bl a').unbind('click').bind('click', function(event) {
    $('#panel-config-frame .scale-bl a').css({'color':'black', 'font-weight':'normal'});
    $(this).css({'color':'red', 'font-weight':'bold'});
    var bl = $(this).html();
    bl = parseInt(bl) / 100;
    $('.work-content').css({'transform':'scale('+bl+', '+bl+')'});
});

/**
 * 获取所有工作站节点树
 */
JsonpAjax(baseApiPath + 'layout/wsn/get', '', 'json', function(res) {
    var potionTree = $('#panel-config-frame #wsn-tree').lonixFloat({
        source: res,
        setting: {
            view: {
                showLine: true,
                selectedMulti: false,
                dblClickExpand: false,
                showIcon: false
            },
            data : {
                simpleData: {
                    enable: true,
                    idKey: "orgCode",
                    pIdKey: "parentCode",
                    rootPId:""
                }
            }
        },
        searchField: 'name',
        target: $('#panel-config-frame .cur-path'),
        primary: function (nodes) {
            var node = nodes[0];
            var count = node.level;
            var lis = '';
            $('#panel-config-frame #wsn-id').val(node.orgCode);
            lis += ('<li>'+node.name+'</li>');
            var temp = potionTree.ztree.getNodesByParam("orgCode", node.parentCode)[0];
            for (var i = count-1; i >= 0; i--) {
                lis = ('<li>'+temp.name+'</li>') + lis;
                temp = potionTree.ztree.getNodesByParam("orgCode", temp.parentCode)[0];
            }
            $('#panel-config-frame .cur-path ul').html(lis);
            $('#wsn-tree').fadeUp();
            JsonpAjax(baseApiPath + 'layout/device/get?workId='+node.orgCode, '', 'json', function(res){
                var list = res;
                var options = '<option value="-1">不绑定</option>';
                for (var i = 0; i < list.length; i++) {
                    options += '<option value="'+list[i].orgCode+'">'+list[i].name+'</option>';
                }
                $('#panel-config-frame [name="bind-device"]').html(options);
            }, false);
            findData(node.orgCode);
        }
    });
}, false);

/**
 * 查询数据
 * @param id 工作站ID
 */
var deviceTree={};
var layoutCache = {};
function findData (id) {
    if (!isEmpty(structureTree)) {
        var allNodes = structureTree.getNodes();
        for (var i = 0; i < allNodes.length; i++) {
            structureTree.removeNode(allNodes[i]);
        }
    }
    data = [];
    JsonpAjax(baseApiPath + 'layout/' + id, '', 'json', function(res){
        if (!isEmpty(res)) {
            data = res['subjects'];
        }
        layoutCache = res;
        var users = res['users'];
        var options = '<option value="-1">全局公共</option><option value="-2">工作站公共</option>';
        if (!isEmpty(users) && users.length > 0) {
            for (var i = 0; i < users.length; i++) {
                var user = users[i];
                var sel = res['curUserId'] == user.id ? ' selected ' : '';
                options += '<option '+sel+' value="'+user.id+'">'+user.userName+'</option>';
            }
        }
        $('#panel-config-frame .layout-user-list select').html(options);

        var mains = res['mains'];
        var newOption = '<option value="-99">新建方案</option>';
        var publicOption = '';
        var wokOption = '';
        var privateOption = '';
        if (!isEmpty(mains) && mains.length > 0) {
            for (var i = 0; i < mains.length; i++) {
                var main = mains[i];
                var seled = '';
                if (main.selectFlag == 1) {
                    seled = ' selected ';
                }
                if (!isEmpty(main.belongUser)) {
                    if (privateOption == '') {
                        privateOption = '<optgroup data-value="private" label="私有方案">';
                    }
                    privateOption += '<option '+seled+' value="'+main.id+'">'+main.workstationName+'</option>';
                } else {
                    if (!isEmpty(main.workstationId)) {
                        if (wokOption == '') {
                            wokOption = '<optgroup data-value="public" label="工作站公共">';
                        }
                        wokOption += '<option '+seled+' value="'+main.id+'">'+main.workstationName+'</option>';
                    } else {
                        if (publicOption == '') {
                            publicOption = '<optgroup data-value="public" label="全局公共">';
                        }
                        publicOption += '<option '+seled+' value="'+main.id+'">'+main.workstationName+'</option>';
                    }
                }

            }
        }
        publicOption += publicOption == ''?'':'</optgroup>';
        wokOption += wokOption == '' ? '' : '</optgroup>'
        privateOption += privateOption == ''?'':'</optgroup>';
        $('#panel-config-frame .layout-programme select').html(newOption+publicOption+wokOption+privateOption);

        // 触发一下用户下拉
        onUserSelect($('#panel-config-frame .layout-user-list select')[0]);

    }, false);
    JsonpAjax(baseApiPath + 'layout/device/get?workId='+id, '', 'json', function(res) {
        deviceTree = $('#panel-config-frame #device-tree').lonixFloat({
            float:'right',
            source: res,
            setting: {
                view: {
                    showLine: true,
                    selectedMulti: false,
                    dblClickExpand: false,
                    showIcon: false
                },
                data : {
                    simpleData: {
                        enable: true,
                        idKey: "orgCode",
                        pIdKey: "parentCode",
                        rootPId:""
                    }
                }
            },
            searchField: 'name',
            target : $('#panel-config-frame #device-id'),
            primary : function (nodes) {
                $('#panel-config-frame #device-id').val(nodes[0].name);
                $('#panel-config-frame #device-id-value').val(nodes[0].orgCode);
                $('#panel-config-frame #device-tree').fadeUp();
                var id = $('#panel-config-frame .work-item.cur').attr('id');
                var nodes = structureTree.getNodesByParam('id', id);
                if (nodes.length == 0) {
                    return;
                }
                nodes[0]['deviceId'] = $('#panel-config-frame').find('#device-id-value').val();
            },
            cancel : function () {
                $('#panel-config-frame #wsn-id').val('');
                $('#panel-config-frame #device-id').val('');
            }
        });
    }, false);
}

/**
 * 当用户被选中时触发事件
 */
function onUserSelect(sel) {
    var userId = $(sel).val();
    var mains = layoutCache['mains'];
    var subjects = layoutCache['subjects'];
    $('#panel-config-frame .layout-programme select optgroup[data-value="private"] option').hide();
    $('#panel-config-frame .layout-programme select optgroup').show();
    var flag = false;
    // 当选择到公共（及某用户私有方案时
    if (userId == '-1') {
        for (var i = 0; i < mains.length; i++) {
            if (mains[i].publicFlag == '1') {
                if (mains[i].selectFlag == '1') {
                    // 级联触发方案
                    $('#panel-config-frame .layout-programme select').val(mains[i].id);
                    onPlanSelect($('#panel-config-frame .layout-programme select')[0]);
                    flag = true;
                }
            }
        }
        // 私有方案
    } else {
        for (var i = 0; i < mains.length; i++) {
            if (mains[i].belongUser == userId) {
                if (mains[i].selectFlag == '1') {
                    // 级联触发方案
                    $('#panel-config-frame .layout-programme select').val(mains[i].id);
                    onPlanSelect($('#panel-config-frame .layout-programme select')[0]);
                    flag = true;
                }
                $('#panel-config-frame .layout-programme select option[value="'+mains[i].id+'"]').show();
            }
        }
    }
    if (!flag) {
        $('#panel-config-frame .layout-programme select').val('-99');
        onPlanSelect($('#panel-config-frame .layout-programme select')[0]);
    }
    // if ($('#panel-config-frame .layout-programme select optgroup[data-value="private"] option:visible').length == 0) {
    //     $('#panel-config-frame .layout-programme select optgroup[data-value="private"]').hide();
    // } else {
    //     $('#panel-config-frame .layout-programme select optgroup[data-value="private"]').show();
    // }
}

// 结构树
var structureTree;
function initStructureTree (list) {
    var sn = 'structureTree-' + new Date().getTime();
    if ($('.slide-menu').find('ul').length == 0) {
        $('.slide-menu').append('<ul class="ztree" id="'+sn+'"></ul>');
    } else {
        sn = $('.slide-menu').find('ul:first-child').attr('id');
    }
    structureTree = $.fn.zTree.init($('#' + sn), {
        check : {
            enable: false
        },
        view : {
            showLine : true,
            selectedMulti : true,
            showIcon: false
        },
        data : {
            simpleData : {
                enable : true,
                idKey : 'id',
                pIdKey : 'parentId'
            }
        },
        callback: {
            onClick: function (event, treeId, treeNode) {
                $('#panel-config-frame #' + treeNode.id).trigger('dbclick');
            }
        }
    }, list);
    structureTree.expandAll(true);

    var nodes = structureTree.getNodes();
    $('#panel-config-frame .work-content').html('');
    for (var i = 0; i < nodes.length; i++) {
        var parentId = nodes[i].parentId;
        if (isEmpty(parentId)) {
            parentId = '.work-content';
        } else {
            parentId = '#'+parentId;
        }
        displayWorkElement($('#panel-config-frame '+parentId), nodes[i], nodes[i].id);
    }

    $('.work-content').bind('click', function(event) {
        $('.work-item.cur').removeClass('cur');
        $('[name="info-width"]').val('');
        $('[name="info-height"]').val('');
        $('[name="info-x"]').val('');
        $('[name="info-y"]').val('');
        $('#panel-config-frame #device-id').val('');
        $('#panel-config-frame #device-id-value').val('');
    });
}

//    id : '1',
//    pId : '',
//    type : 'panel',
//    htmlTag : 'div',
//    name : '最大容器',
//    title : '',
//    htmlPid :'',
//    cssInfo : '{"position":"absolute","overflow":"hidden","top":"0","left":"0","right":"0","bottom":"0"}'

/**
 * 显示工作元素（从数据库中读取出来后展示的方法
 */
function displayWorkElement (parent, item) {
    var target;
    var newNode = {};
    newNode['id'] = goblesn;
    newNode['parentId'] = parent.attr('id') == undefined ? '' : parent.attr('id');
    newNode['type'] = item.type;
    target = document.createElement(''+item.htmlTag+'');
    target.setAttribute('data-type', item.clientType);
    if (item.clientType == 'Lonix.BasePanel') {
        var title = document.createElement('input')
        title.type = 'text';
        title.value = item.title;
        title.className = 'panel-title';
        target.appendChild(title);
    }
    target.setAttribute('data-value', item.id);
    target.setAttribute('id', item.id);
    target.className = 'work-item';
    target.ondblclick = function (e) {
        if ($(this).attr('id') == '1') return;
        if ($(this).hasClass('cur')) {
            $(this).removeClass('cur');
            $('[name="info-width"]').val('');
            $('[name="info-height"]').val('');
            $('[name="info-x"]').val('');
            $('[name="info-y"]').val('');
            $('#panel-config-frame #device-id').val('');
            $('#panel-config-frame #device-id-value').val('');
            return;
        }
        $('.work-item.cur').removeClass('cur');
        $(this).addClass('cur');
        $('#panel-config-frame #device-id').val('');
        $('#panel-config-frame #device-id-value').val('');
        deviceTree.ztree.cancelSelectedNode();
        var id = $(this).attr('id');
        var nodes = structureTree.getNodesByParam('id', id);
        if (nodes.length > 0) {
            var deviceId = nodes[0]['deviceId'];
            var nodes = deviceTree.ztree.getNodesByParam('orgCode', deviceId);
            if (nodes.length > 0) {
                deviceTree.ztree.selectNode(nodes[0]);
                deviceTree.primary(nodes);
            }
        }
        var curWidth = $(this).width();
        var curHeight = $(this).height();
        var x = $(this).css('left');
        var y = $(this).css('top');
        x = parseFloat(x);
        y = parseFloat(y);
        $('[name="info-width"]').val(curWidth);
        $('[name="info-height"]').val(curHeight);
        $('[name="info-x"]').val(x);
        $('[name="info-y"]').val(y);
        e.stopPropagation();
    }
    target.onmousedown = function (e) {
        if ($(this).attr('id') == '1') return;
        $('#panel-config-frame .work-item').css({'z-index':'auto'});
        $(this).css({'z-index':'10'});
        $(this).attr('data-xxx', $(this).css('left'));
        $(this).attr('data-yyy', $(this).css('top'));
        $(this).attr('data-mx', e.clientX);
        $(this).attr('data-my', e.clientY);
        $(this).attr('data-move', '1');
        e.stopPropagation();
    }
    target.onmouseup = function (e) {
        $(this).attr('data-move', 0);
        e.stopPropagation();
    }
    target.onmousemove = function (e) {
        if ($(this).attr('data-move') == 1) {
            var x = $(this).attr('data-xxx');
            var y = $(this).attr('data-yyy');
            var mx = $(this).attr('data-mx');
            var my = $(this).attr('data-my');
            $(this).css({'left':e.clientX-mx+parseInt(x)+'px', 'top':e.clientY-my+parseInt(y)+'px'});
            $(this).attr('data-xxx', $(this).css('left'));
            $(this).attr('data-yyy', $(this).css('top'));
            $(this).attr('data-mx', e.clientX);
            $(this).attr('data-my', e.clientY);
        }
        e.stopPropagation();
    }
    parent.append(target);
    $(target).css(JSON.parse(item.cssInfo));
    if (!isEmpty(item.children)) {
        for (var i = 0; i < item.children.length; i++) {
            displayWorkElement($(target), item.children[i]);
        }
    }
}

/**
 * 创建工作元素
 * @parent 父级元素 jquery对象
 * @typ 节点类型
 * @val 节点值
 */
function createWorkElement (parent, typ, val) {
    if (structureTree == undefined) {
        notification({'title':'提示', 'message':'请先选择工作站后再添加元素'}, 'info')
        return;
    }
    var target;
    var newNode = {};
    var styleInfo = {};
    newNode['id'] = goblesn;
    newNode['parentId'] = parent.attr('id') == undefined ? '' : parent.attr('id');
    newNode['type'] = typ;
    if (typ == "Lonix.BasePanel") {
        target = document.createElement('div');
        var title = document.createElement("input");
        title.type = 'text';
        title.className = 'panel-title';
        title.value = '空白容器';
        target.appendChild(title);
        target.style.width = '500px';
        target.style.height = '350px';
        styleInfo['width'] = '500px'
        styleInfo['height'] = '350px'
        newNode['name'] = '空白容器';
        newNode['title'] = '空白容器';
        newNode['htmlTag'] = 'div';
    } else if (typ == "Lonix.RoadGate") {
        target = document.createElement('div');
        target.style.width = '139px';
        target.style.height = '100px';
        styleInfo['width'] = '139px'
        styleInfo['height'] = '100px'
        target.style.backgroundImage = 'url("images/work-item/道闸_正常.png")';
        styleInfo['backgroundImage'] = 'url("images/work-item/道闸_正常.png")';
        newNode['name'] = '道闸';
        newNode['title'] = '道闸';
        newNode['htmlTag'] = 'div';
    } else if (typ == "Lonix.MonitorCenter") {
        target = document.createElement('div');
        target.style.width = '617px';
        target.style.height = '314px';
        target.style.backgroundImage = 'url("images/work-item/无视频.png")';
        styleInfo['width'] = '617px';
        styleInfo['height'] = '314px';
        styleInfo['backgroundImage'] = 'url("images/work-item/无视频.png")';
        newNode['name'] = '视频源';
        newNode['title'] = '视频源';
        newNode['htmlTag'] = 'div';
    } else if (typ == "Lonix.CarInformation") {
        target = document.createElement('div');
        target.style.width = '578px';
        target.style.height = '435px';
        target.style.backgroundImage = 'url("images/work-item/图片控件.jpg")';
        styleInfo['width'] = '578px';
        styleInfo['height'] = '435px';
        styleInfo['backgroundImage'] = 'url("images/work-item/图片控件.jpg")';
        newNode['name'] = '图片控件';
        newNode['title'] = '图片控件';
        newNode['htmlTag'] = 'div';
    } else if (typ == "Lonix.OperatorInfo") {
        target = document.createElement('div');
        target.style.width = '566px';
        target.style.height = '317px';
        target.style.backgroundImage = 'url("images/work-item/基本信息.png")';
        styleInfo['width'] = '566px';
        styleInfo['width'] = '317px';
        styleInfo['backgroundImage'] = 'url("images/work-item/基本信息.png")';
        newNode['name'] = '基本信息';
        newNode['title'] = '基本信息';
        newNode['htmlTag'] = 'div';
    } else if (typ == "Lonix.RemainingUnit") {
        target = document.createElement('div');
        target.style.width = '566px';
        target.style.height = '271px';
        target.style.backgroundImage = 'url("images/work-item/余位统计.png")';
        styleInfo['width'] = '566px';
        styleInfo['height'] = '217px';
        styleInfo['backgroundImage'] = 'url("images/work-item/余位统计.png")';
        newNode['name'] = '余位统计';
        newNode['title'] = '余位统计';
        newNode['htmlTag'] = 'div';
    } else if (typ == "Lonix.MultiTab") {
        target = document.createElement('div');
        target.style.width = '1339px';
        target.style.height = '271px';
        target.style.backgroundImage = 'url("images/work-item/最近数据.png")';
        styleInfo['width'] = '1339px';
        styleInfo['height'] = '271px';
        styleInfo['backgroundImage'] = 'url("images/work-item/最近数据.png")';
        newNode['name'] = '最近数据';
        newNode['title'] = '最近数据';
        newNode['htmlTag'] = 'div';
    } else if (typ == 'Lonix.ControlPanel') {
        target = document.createElement('div');
        target.style.width = '100%';
        target.style.height = '80px';
        styleInfo['width'] = '100%';
        styleInfo['height'] = '80px';
        newNode['name'] = '底部菜单';
        newNode['title'] = '底部菜单';
        newNode['htmlTag'] = 'div';
    } else if (typ == 'Lonix.DetailsOfEntryAndExit') {
        target = document.createElement('div');
        target.style.width = '200px';
        target.style.height = '150px';
        target.style.backgroundColor = '#eee';
        target.style.backgroundImage = 'url(images/bill.png)';
        target.style.backgroundSize = '50% 50%';
        target.style.backgroundPosition = 'center';
        styleInfo['width'] = '100%';
        styleInfo['height'] = '80px';
        styleInfo['backgroundImage'] = 'url(images/bill.png)';
        styleInfo['backgroundSize'] = '50% 50%';
        styleInfo['backgroundPosition'] = 'center';
        styleInfo['backgroundColor'] = '#eee';
        newNode['name'] = '结算明细清单';
        newNode['title'] = '结算明细清单';
        newNode['htmlTag'] = 'div';
    }
    target.style.backgroundSize = '100% 100%';
    target.style.backgroundRepeat = 'no-repeat';


    styleInfo['backgroundSize'] = '100% 100%';
    styleInfo['backgroundRepeat'] = 'no-repeat';

    target.setAttribute('data-type', typ);
    target.setAttribute('data-value', val);

    target.className = 'work-item';
    target.style.position = 'absolute';
    target.style.top = 0;
    target.style.left = 0;
    target.style.border = "1px solid #cccccc";

    styleInfo['position'] = 'absolute';
    styleInfo['top'] = 0;
    styleInfo['left'] = 0;
    styleInfo['border'] = '1px solid #cccccc';

    target.ondblclick = function (e) {
        if ($(this).attr('id') == '1') return;
        if ($(this).hasClass('cur')) {
            $(this).removeClass('cur');
            $('[name="info-width"]').val('');
            $('[name="info-height"]').val('');
            $('[name="info-x"]').val('');
            $('[name="info-y"]').val('');
            $('#panel-config-frame #device-id').val('');
            $('#panel-config-frame #device-id-value').val('');
            return;
        }
        $('.work-item.cur').removeClass('cur');
        $(this).addClass('cur');
        $('#panel-config-frame #device-id').val('');
        $('#panel-config-frame #device-id-value').val('');
        deviceTree.ztree.cancelSelectedNode();
        var id = $(this).attr('id');
        var nodes = structureTree.getNodesByParam('id', id);
        if (nodes.length > 0) {
            var deviceId = nodes[0]['deviceId'];
            var nodes = deviceTree.ztree.getNodesByParam('orgCode', deviceId);
            if (nodes.length > 0) {
                deviceTree.ztree.selectNode(nodes[0]);
                deviceTree.primary(nodes);
            }
        }
        var curWidth = $(this).width();
        var curHeight = $(this).height();
        var x = $(this).css('left');
        var y = $(this).css('top');
        x = parseFloat(x);
        y = parseFloat(y);
        $('[name="info-width"]').val(curWidth);
        $('[name="info-height"]').val(curHeight);
        $('[name="info-x"]').val(x);
        $('[name="info-y"]').val(y);
        e.stopPropagation();
    }
    target.onmousedown = function (e) {
        if ($(this).attr('id') == '1') return;
        $('#panel-config-frame .work-item').css({'z-index':'auto'});
        $(this).css({'z-index':'10'});
        $(this).attr('data-xxx', $(this).css('left'));
        $(this).attr('data-yyy', $(this).css('top'));
        $(this).attr('data-mx', e.clientX);
        $(this).attr('data-my', e.clientY);
        $(this).attr('data-move', '1');
        e.stopPropagation();
    }
    target.onmouseup = function (e) {
        $(this).attr('data-move', 0);
        e.stopPropagation();
    }
    target.onmousemove = function (e) {
        if ($(this).attr('data-move') == 1) {
            var x = $(this).attr('data-xxx');
            var y = $(this).attr('data-yyy');
            var mx = $(this).attr('data-mx');
            var my = $(this).attr('data-my');
            $(this).css({'left':e.clientX-mx+parseInt(x)+'px', 'top':e.clientY-my+parseInt(y)+'px'});
            // console.log(mx+':'+e.clientX);
            $(this).attr('data-xxx', $(this).css('left'));
            $(this).attr('data-yyy', $(this).css('top'));
            $(this).attr('data-mx', e.clientX);
            $(this).attr('data-my', e.clientY);
        }
        e.stopPropagation();
    }
    newNode['cssInfo'] = JSON.stringify(styleInfo);
    parent.append(target);
    target.id = goblesn;
    var parentNode = structureTree.getNodesByParam("id", parent.attr('id'), null)[0];
    parentNode = parentNode == undefined ? structureTree.getNodesByParam("id", '1')[0] : parentNode;
    newNode = structureTree.addNodes(parentNode, newNode);
    goblesn++;
}
var resolutionSelect;
function initDropDown() {
    resolutionSelect = $('.resolution-button a').lonixDownList({source:[
        {"title":"1920*1080", "value":"1920*1080"},
        {"title":"1600*1024", "value":"1600*1024"},
        {"title":"1600*900","value":"1600*900"},
        {"title":"1440*900","value":"1440*900"},
        {"title":"1366*768","value":"1366*768"},
        {"title":"1360*768","value":"1360*768"},
        {"title":"1280*1024","value":"1280*1024"},
        {"title":"1280*960","value":"1280*960"},
        {"title":"1280*800","value":"1280*800"},
        {"title":"1280*768","value":"1280*768"},
        {"title":"1280*720","value":"1280*720"},
        {"title":"1280*960","value":"1280*960"},
        {"title":"1152*864","value":"1152*864"},
        {"title":"1090*1080","value":"1090*1080"},
        {"title":"1080*960","value":"1080*960"},
        {"title":"1024*768","value":"1024*768"},
        {"title":"800*600","value":"800*600"}
        ],
        selectFunction : function(val) {
            initWorkSpace();
        }
    });
}
initDropDown();

/**
 * 初始化工作空间
 */
function initWorkSpace () {
    var resolution = resolutionSelect.val();
    var resolutions = resolution.split('*');
    var width = resolutions[0];
    var height = resolutions[1];
    var tempHeight = $('#panel-config-frame .body-content').height();
    var tempWidth = tempHeight / height * width;
    $('#panel-config-frame .work-content').css({'width':width, 'height':height});
}
initWorkSpace();

/**
 * 展开侧边栏
 */
var slideStatus = 0;
function openSlideMenu(that) {
    if (slideStatus == 0) {
        $('.slide-menu').show();
        $('.body-content').css({'left':'151px'});
        slideStatus = 1;
    } else {
        $('.slide-menu').hide();
        $('.body-content').css({'left':'0'});
        slideStatus = 0;
    }
}

var properStatus = 0;
function openLayoutPropertyPanel() {
    if (properStatus == 0) {
        $('#panel-config-frame .properties-menu').hide();
        $('#panel-config-frame .bottom-footer').css('right', '0px');
        properStatus = 1;
    } else {
        $('#panel-config-frame .properties-menu').show();
        $('#panel-config-frame .bottom-footer').css('right', '200px');
        properStatus = 0;
    }
}

/**
 * 当选择方案时触发事件
 */
function onPlanSelect (sel) {
    data = [];
    data.push({
        id : '1',
        parentId : '',
        type : 'panel',
        htmlTag : 'div',
        name : '最大容器',
        title : '',
        cssInfo : '{"position":"absolute","overflow":"hidden","top":"0","left":"0","right":"0","bottom":"0"}'
    });
    if ($(sel).val() == '-99') {
        $('#panel-config-frame .layout-name input[type="text"]').val('');
        $('#panel-config-frame .work-content').html('');
        initStructureTree(data);
    } else {
        $('#panel-config-frame .layout-name input[type="text"]').val($(sel).find('option:selected').text());
        var mains = layoutCache['mains'];
        var subjects = layoutCache['subjects'];
        for (var i = 0; i < mains.length; i++) {
            if (mains[i].id == $(sel).val()) {
                $('#panel-config-frame .resolution-button').find('[data-value="'+mains[i].resolution+'"]').click();
                break;
            }
        }
        var needSubjects = [];
        for (var i = 0; i < subjects.length; i++) {
            if (subjects[i].mainId == $(sel).val()) {
                needSubjects.push(subjects[i]);
            }
        }
        data = data.concat(needSubjects);
        initStructureTree(data);
    }
}
/**
 * 当方案被加载后触发事件
 */
function onPlanLoaded (sel) {

}

/**
 * 展开分辨率选项
 */
function openResolution(that) {

}
function deleteLayoutMainById() {
    var mainId = $('#panel-config-frame .layout-programme select').val();
    if (isEmpty(mainId)) {
        notification({'title':'提示', 'message':'请线选择需要删除的方案'},'info');
        return;
    }
    if (confirm("是否确认删除该方案？")) {
        JsonpAjax(baseApiPath + '/layout/delete/'+mainId, null, 'json', function() {
            findData($('#panel-config-frame #wsn-id').val());
        },false);
    }
}
/**
 * 删除工作项
 */
function deleteWorkItem(){
    var id = $('.work-item.cur').attr('id');
    var node = structureTree.getNodesByParam('id', id)[0];
    structureTree.removeNode(node);
    $('.work-item.cur').remove();
}

/**
 * 保存这套方案
 */
function saveThisLayout() {
    var param = {};
    // 获取当前层级结构保存
    var nodes = structureTree.getNodes();
    // 如果层级结构大于1，则说明拥有布局就保存
    itLayout(nodes[0]);
    param['nodes'] = nodes;
    nodes[0]['layout-id'] = $('#panel-config-frame #layout-id').val();
    nodes[0]['resolution'] = resolutionSelect.val();
    nodes[0]['wsnId'] = $('#panel-config-frame #wsn-id').val();
    if (nodes[0]['wsnId'] == '') {
        alert('请重新选择工作站！');
        console.log('请重新选择工作站！');
        return;
    }
    nodes[0]['user'] = $('#panel-config-frame .layout-user-list select').val();
    nodes[0]['panel-id'] = $('#panel-config-frame .layout-programme select').val();
    nodes[0]['layout-name'] = $('#panel-config-frame .layout-name input[type="text"]').val();
    // 获取当前工作站ID
    if (nodes[0].children && nodes[0].children.length > 0) {
        JsonpAjax(baseApiPath + 'layout/save', JSON.stringify(param), 'json', function (res){
            findData(nodes[0]['wsnId']);
        }, false);
    } else {
        notification({'title':'提示', 'message':'未添加任何布局，保存失败'}, 'info');
    }
}

/**
 * 递归层级结构
 * @param node Tree结构节点
 */
function itLayout (node) {
    // 循环构建层级对象（长宽及坐标
    var item = $('#panel-config-frame').find('#' + node.id);
    var x = parseFloat(item.css('left'));
    var y = parseFloat(item.css('top'));
    x = isNaN(x) ? 0 : x;
    y = isNaN(y) ? 0 : y;
    var parentNodes = item.parents('.work-item');
    var workContent = parentNodes.length == 0 ? $('#panel-config-frame #1') : parentNodes;
    var width = workContent.width();
    var height = workContent.height();
    width = parseFloat(width);
    height = parseFloat(height);
    width = isNaN(width) ? 0 : width;
    height = isNaN(height) ? 0 : height;
    var curWidth = item.width();
    var curHeight = item.height();
    var resultW = (parseFloat(curWidth) / width) * 100;
    var resultH = (parseFloat(curHeight) / height) * 100;
    var resultX = x / width * 100;
    var resultY = y / height * 100;
    node['x'] = resultX.toFixed(2);
    node['y'] = resultY.toFixed(2);
    node['width'] = resultW.toFixed(2);
    node['height'] = resultH.toFixed(2);
    node['clientType'] = item.attr('data-type');
    if (node['clientType'] == 'Lonix.BasePanel') {
        var title = $('#panel-config-frame #' + node['id']).find('.panel-title').val();
        node['title'] = title;
    }
    node['cssInfo'] = item[0].style;
    if (!isEmpty(node.children) && node.children.length > 0) {
        for (var i = 0; i < node.children.length; i++) {
            itLayout(node.children[i]);
        }
    }
}

/**
 * 缩放窗口
 * @param a 按钮对象
 */
function scalePanel (a) {
    if ($(a).html() == '缩小') {
        $('#panel-config-frame').parents('li')[0].style.position = 'relative';
        $(a).html('全屏');
    } else {
        $('#panel-config-frame').parents('li')[0].style.position = 'inherit';
        $(a).html('缩小');
    }
}

$('[name="info-width"]').bind('keyup', function() {
    $('.work-item.cur').css({'width':$(this).val()==''?0:$(this).val()+'px'});
});
$('[name="info-height"]').bind('keyup', function() {
    $('.work-item.cur').css({'height':$(this).val()==''?0:$(this).val()+'px'});
});
$('[name="info-x"]').bind('keyup', function() {
    $('.work-item.cur').css({'left':$(this).val()==''?0:$(this).val()+'px'});
});
$('[name="info-y"]').bind('keyup', function() {
    $('.work-item.cur').css({'top':$(this).val()==''?0:$(this).val()+'px'});
});

$('#panel-config-frame #scale-button').click();